<template>
  <div class="table-sql-preview">
    <div class="mb-4 flex justify-between items-center">
      <h3 class="text-sm font-medium text-gray-700">SQL 预览</h3>
      <div class="flex space-x-2">
        <el-select 
          v-model="sqlType" 
          size="small"
          class="w-32 hover:border-gray-400 focus:ring-1 focus:ring-blue-500 transition-all"
        >
          <el-option label="创建表" value="create" />
          <el-option v-if="!isNewTable" label="修改表" value="alter" />
        </el-select>
        <el-button 
          size="small" 
          @click="copyToClipboard" 
          type="primary" 
          plain
          class="hover:bg-blue-100 transition-colors"
        >
          <el-icon><DocumentCopy /></el-icon>复制
        </el-button>
      </div>
    </div>

    <div class="bg-gray-50 border border-gray-200 rounded-lg shadow-sm p-4 relative">
      <!-- SQL语法高亮显示 -->
      <pre class="text-sm font-mono whitespace-pre-wrap overflow-x-auto max-h-96 text-gray-800 p-2 bg-gray-50 rounded-md">{{ generatedSql }}</pre>
      
      <!-- 复制成功提示 -->
      <div 
        v-if="copied" 
        class="absolute bottom-4 right-4 bg-green-100 text-green-700 px-3 py-1 rounded-md text-sm font-medium shadow-sm fade-out"
      >
        已复制到剪贴板
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue';
import { DocumentCopy } from '@element-plus/icons-vue';

const props = defineProps({
  tableData: {
    type: Object,
    required: true
  },
  isNewTable: {
    type: Boolean,
    default: true
  },
  databaseType: {
    type: String,
    default: 'mysql'
  }
});

const sqlType = ref('create');
const copied = ref(false);

// 自动切换SQL类型
watch(() => props.isNewTable, (newVal) => {
  sqlType.value = newVal ? 'create' : 'alter';
});

// 生成SQL
const generatedSql = computed(() => {
  return sqlType.value === 'create' 
    ? generateCreateTableSQL() 
    : generateAlterTableSQL();
});

// 生成创建表SQL
const generateCreateTableSQL = () => {
  // 获取数据库特定的SQL生成器
  const generator = getSqlGenerator();
  return generator.generateCreateSQL(props.tableData);
};

// 生成修改表SQL
const generateAlterTableSQL = () => {
  // 获取数据库特定的SQL生成器
  const generator = getSqlGenerator();
  return generator.generateAlterSQL(props.tableData);
};

// 根据数据库类型获取SQL生成器
const getSqlGenerator = () => {
  switch (props.databaseType) {
    case 'mysql':
      return getMySQLGenerator();
    case 'postgresql':
      return getPostgreSQLGenerator();
    case 'sqlite':
      return getSQLiteGenerator();
    case 'sqlserver':
      return getSQLServerGenerator();
    case 'dameng':
      return getDaMengGenerator();
    default:
      return getMySQLGenerator(); // 默认使用MySQL
  }
};

// MySQL SQL生成器
const getMySQLGenerator = () => {
  return {
    // 生成创建表SQL
    generateCreateSQL(tableData) {
      let sql = `CREATE TABLE \`${tableData.name}\` (\n`;
      
      // 添加列定义
      const columnDefinitions = tableData.columns.map(column => {
        let def = `  \`${column.name}\` ${column.type.toUpperCase()}`;
        
        // 添加长度或值
        if (column.length && this.needsLength(column.type)) {
          def += `(${column.length})`;
        } else if (column.values && this.needsValues(column.type)) {
          def += `(${column.values.split(',').map(v => `'${v.trim()}'`).join(', ')})`;
        }
        
        // 不为空
        if (column.notNull) {
          def += ' NOT NULL';
        }
        
        // 自增
        if (column.autoIncrement) {
          def += ' AUTO_INCREMENT';
        }
        
        // 默认值
        if (column.defaultValue) {
          if (['CURRENT_TIMESTAMP', 'NULL'].includes(column.defaultValue.toUpperCase())) {
            def += ` DEFAULT ${column.defaultValue.toUpperCase()}`;
          } else {
            def += ` DEFAULT '${column.defaultValue}'`;
          }
        }
        
        // 注释
        if (column.comment) {
          def += ` COMMENT '${column.comment}'`;
        }
        
        return def;
      });
      
      sql += columnDefinitions.join(',\n');
      
      // 添加主键
      const primaryColumns = tableData.columns
        .filter(col => col.primaryKey)
        .map(col => `\`${col.name}\``);
        
      if (primaryColumns.length > 0) {
        sql += `,\n  PRIMARY KEY (${primaryColumns.join(', ')})`;
      }
      
      // 添加索引
      if (tableData.indexes && tableData.indexes.length > 0) {
        for (const index of tableData.indexes) {
          if (!index.name || !index.columns || index.columns.length === 0) {
            continue; // 跳过无效索引
          }
          
          const indexColumns = index.columns.map(col => `\`${col}\``).join(', ');
          sql += `,\n  ${index.type} \`${index.name}\` (${indexColumns})`;
        }
      }
      
      // 添加外键
      if (tableData.foreignKeys && tableData.foreignKeys.length > 0) {
        for (const fk of tableData.foreignKeys) {
          if (!fk.name || !fk.columns || fk.columns.length === 0 || 
              !fk.referenceTable || !fk.referenceColumns || fk.referenceColumns.length === 0) {
            continue; // 跳过无效外键
          }
          
          const fkColumns = fk.columns.map(col => `\`${col}\``).join(', ');
          const refColumns = fk.referenceColumns.map(col => `\`${col}\``).join(', ');
          
          sql += `,\n  CONSTRAINT \`${fk.name}\` FOREIGN KEY (${fkColumns}) REFERENCES \`${fk.referenceTable}\` (${refColumns})`;
          
          // 添加级联操作
          if (fk.updateRule) {
            sql += ` ON UPDATE ${fk.updateRule}`;
          }
          
          if (fk.deleteRule) {
            sql += ` ON DELETE ${fk.deleteRule}`;
          }
        }
      }
      
      // 添加表选项
      sql += `\n) ENGINE=${tableData.engine || 'InnoDB'} DEFAULT CHARSET=${tableData.charset || 'utf8mb4'} COLLATE=${tableData.collation || 'utf8mb4_general_ci'}`;
      
      // 添加高级选项
      if (tableData.advancedOptions) {
        const options = tableData.advancedOptions;
        
        if (options.rowFormat) {
          sql += ` ROW_FORMAT=${options.rowFormat}`;
        }
        
        if (options.autoIncrement && options.autoIncrement > 1) {
          sql += ` AUTO_INCREMENT=${options.autoIncrement}`;
        }
        
        if (options.avgRowLength && options.avgRowLength > 0) {
          sql += ` AVG_ROW_LENGTH=${options.avgRowLength}`;
        }
        
        if (options.keyBlockSize && options.keyBlockSize > 0) {
          sql += ` KEY_BLOCK_SIZE=${options.keyBlockSize}`;
        }
        
        if (options.tablespace) {
          sql += ` TABLESPACE ${options.tablespace}`;
        }
        
        if (options.checksum) {
          sql += ` CHECKSUM=1`;
        }
        
        if (options.packKeys) {
          sql += ` PACK_KEYS=1`;
        }
        
        if (options.delayKeyWrite) {
          sql += ` DELAY_KEY_WRITE=1`;
        }
        
        // 分区选项
        if (options.partition) {
          sql += `\n${options.partition}`;
        }
        
        // 自定义选项
        if (options.custom) {
          sql += ` ${options.custom}`;
        }
      }
      
      // 表注释
      if (tableData.comment) {
        sql += ` COMMENT='${tableData.comment}'`;
      }
      
      sql += ';';
      
      return sql;
    },
    
    // 生成修改表SQL
    generateAlterSQL(tableData) {
      // 这里只是一个简化的实现，实际中应该比较新旧结构差异
      // 完整的ALTER语句生成应该基于与现有表的比较
      
      let sql = `ALTER TABLE \`${tableData.name}\`\n`;
      const alterClauses = [];
      
      // 引擎
      alterClauses.push(`ENGINE=${tableData.engine || 'InnoDB'}`);
      
      // 字符集
      alterClauses.push(`DEFAULT CHARSET=${tableData.charset || 'utf8mb4'}`);
      
      // 排序规则
      alterClauses.push(`COLLATE=${tableData.collation || 'utf8mb4_general_ci'}`);
      
      // 注释
      if (tableData.comment) {
        alterClauses.push(`COMMENT='${tableData.comment}'`);
      }
      
      // 添加高级选项
      if (tableData.advancedOptions) {
        const options = tableData.advancedOptions;
        
        if (options.rowFormat) {
          alterClauses.push(`ROW_FORMAT=${options.rowFormat}`);
        }
        
        if (options.autoIncrement && options.autoIncrement > 1) {
          alterClauses.push(`AUTO_INCREMENT=${options.autoIncrement}`);
        }
      }
      
      sql += alterClauses.join(',\n');
      sql += ';';
      
      return sql + '\n\n/* 注意: 这只是表级别的修改。列和索引的修改需要添加对应的ALTER TABLE语句 */';
    },
    
    // 类型是否需要长度
    needsLength(type) {
      return ['varchar', 'char', 'int', 'tinyint', 'smallint', 'mediumint', 'bigint', 
              'decimal', 'float', 'double', 'bit', 'binary', 'varbinary'].includes(type);
    },
    
    // 类型是否需要值列表
    needsValues(type) {
      return ['enum', 'set'].includes(type);
    }
  };
};

// PostgreSQL SQL生成器
const getPostgreSQLGenerator = () => {
  return {
    // 生成创建表SQL
    generateCreateSQL(tableData) {
      const schema = (tableData.schema || tableData.advancedOptions?.schema || 'public');
      let sql = `CREATE TABLE "${schema}"."${tableData.name}" (\n`;
      
      // 添加列定义
      const columnDefinitions = tableData.columns.map(column => {
        // 处理serial类型
        if (['serial', 'bigserial', 'smallserial'].includes(column.type)) {
          let def = `  "${column.name}" ${column.type.toUpperCase()}`;
          
          // 主键
          if (column.primaryKey) {
            def += ' PRIMARY KEY';
          }
          
          // 注释
          if (column.comment) {
            // PostgreSQL中，列注释需要单独添加
          }
          
          return def;
        }
        
        let def = `  "${column.name}" ${column.type.toUpperCase()}`;
        
        // 添加长度或值
        if (column.length && this.needsLength(column.type)) {
          def += `(${column.length})`;
        }
        
        // 不为空
        if (column.notNull) {
          def += ' NOT NULL';
        }
        
        // 主键
        if (column.primaryKey && !['serial', 'bigserial', 'smallserial'].includes(column.type)) {
          def += ' PRIMARY KEY';
        }
        
        // 默认值
        if (column.defaultValue) {
          if (['CURRENT_TIMESTAMP', 'NULL', 'now()'].includes(column.defaultValue.toUpperCase())) {
            def += ` DEFAULT ${column.defaultValue.toUpperCase()}`;
          } else {
            def += ` DEFAULT '${column.defaultValue}'`;
          }
        }
        
        return def;
      });
      
      sql += columnDefinitions.join(',\n');
      
      // 添加约束（除了列定义中的主键）
      const primaryColumns = tableData.columns
        .filter(col => col.primaryKey && !['serial', 'bigserial', 'smallserial'].includes(col.type))
        .map(col => `"${col.name}"`);
        
      if (primaryColumns.length > 1) {
        // 如果主键是多列的，添加表级约束
        sql += `,\n  PRIMARY KEY (${primaryColumns.join(', ')})`;
      }
      
      // 添加索引和约束将在表创建后添加
      
      sql += '\n)';
      
      // 添加高级选项
      if (tableData.advancedOptions) {
        const options = tableData.advancedOptions;
        const withOptions = [];
        
        if (options.fillfactor && options.fillfactor < 100) {
          withOptions.push(`fillfactor = ${options.fillfactor}`);
        }
        
        if (options.autovacuum && options.autovacuum !== 'DEFAULT') {
          withOptions.push(`autovacuum_enabled = ${options.autovacuum === 'ON' ? 'true' : 'false'}`);
        }
        
        if (options.withOids) {
          withOptions.push('oids = true');
        }
        
        if (options.storageParameters) {
          withOptions.push(options.storageParameters);
        }
        
        if (withOptions.length > 0) {
          sql += `\nWITH (${withOptions.join(', ')})`;
        }
        
        // 表空间
        if (options.tablespace) {
          sql += `\nTABLESPACE ${options.tablespace}`;
        }
        
        // 自定义选项
        if (options.custom) {
          sql += `\n${options.custom}`;
        }
      }
      
      sql += ';';
      
      // 添加列注释
      tableData.columns.forEach(column => {
        if (column.comment) {
          sql += `\n\nCOMMENT ON COLUMN "${schema}"."${tableData.name}"."${column.name}" IS '${column.comment}';`;
        }
      });
      
      // 添加表注释
      if (tableData.comment) {
        sql += `\n\nCOMMENT ON TABLE "${schema}"."${tableData.name}" IS '${tableData.comment}';`;
      }
      
      // 添加索引
      if (tableData.indexes && tableData.indexes.length > 0) {
        sql += '\n';
        for (const index of tableData.indexes) {
          if (!index.name || !index.columns || index.columns.length === 0) {
            continue; // 跳过无效索引
          }
          
          const indexColumns = index.columns.map(col => `"${col}"`).join(', ');
          const indexType = this.getPostgresIndexType(index.type);
          
          sql += `\n\nCREATE ${indexType} INDEX "${index.name}" ON "${schema}"."${tableData.name}" (${indexColumns});`;
        }
      }
      
      return sql;
    },
    
    // 生成修改表SQL
    generateAlterSQL(tableData) {
      const schema = (tableData.schema || tableData.advancedOptions?.schema || 'public');
      let sql = `-- 修改表 ${schema}.${tableData.name}\n`;
      
      // 表重命名示例
      sql += `-- 重命名表\n-- ALTER TABLE "${schema}"."old_name" RENAME TO "${tableData.name}";\n\n`;
      
      // 添加列示例
      sql += `-- 添加列\n-- ALTER TABLE "${schema}"."${tableData.name}" ADD COLUMN "new_column" TEXT;\n\n`;
      
      // 修改列示例
      sql += `-- 修改列\n-- ALTER TABLE "${schema}"."${tableData.name}" ALTER COLUMN "column_name" TYPE VARCHAR(255);\n\n`;
      
      // 添加约束示例
      sql += `-- 添加约束\n-- ALTER TABLE "${schema}"."${tableData.name}" ADD CONSTRAINT "constraint_name" CHECK (condition);\n\n`;
      
      // 表注释
      if (tableData.comment) {
        sql += `-- 设置表注释\nCOMMENT ON TABLE "${schema}"."${tableData.name}" IS '${tableData.comment}';\n\n`;
      }
      
      return sql + '/* 注意: 这只是示例。实际的ALTER语句需要根据与当前表结构的差异自动生成。 */';
    },
    
    // 将通用索引类型转换为PostgreSQL索引类型
    getPostgresIndexType(genericType) {
      switch (genericType.toUpperCase()) {
        case 'UNIQUE':
          return 'UNIQUE';
        case 'HASH':
          return 'HASH';
        case 'GIN':
          return 'GIN';
        case 'GIST':
          return 'GIST';
        case 'BRIN':
          return 'BRIN';
        default:
          return ''; // 默认索引类型
      }
    },
    
    // 类型是否需要长度
    needsLength(type) {
      return ['varchar', 'character', 'char', 'decimal', 'numeric'].includes(type);
    }
  };
};

// SQLite SQL生成器
const getSQLiteGenerator = () => {
  return {
    // 生成创建表SQL
    generateCreateSQL(tableData) {
      let sql = `CREATE TABLE "${tableData.name}" (\n`;
      
      // 添加列定义
      const columnDefinitions = tableData.columns.map(column => {
        let def = `  "${column.name}" ${column.type.toUpperCase()}`;
        
        // 主键
        if (column.primaryKey) {
          def += ' PRIMARY KEY';
          
          // 自增
          if (column.autoIncrement) {
            def += ' AUTOINCREMENT';
          }
        }
        
        // 不为空
        if (column.notNull && !column.primaryKey) { // SQLite中主键已经隐含NOT NULL
          def += ' NOT NULL';
        }
        
        // 默认值
        if (column.defaultValue) {
          if (['CURRENT_TIMESTAMP', 'NULL'].includes(column.defaultValue.toUpperCase())) {
            def += ` DEFAULT ${column.defaultValue.toUpperCase()}`;
          } else {
            def += ` DEFAULT '${column.defaultValue}'`;
          }
        }
        
        return def;
      });
      
      // 添加非单列主键约束
      const primaryColumns = tableData.columns
        .filter(col => col.primaryKey)
        .map(col => `"${col.name}"`);
        
      if (primaryColumns.length > 1) {
        columnDefinitions.push(`  PRIMARY KEY (${primaryColumns.join(', ')})`);
      }
      
      // 添加外键约束
      if (tableData.foreignKeys && tableData.foreignKeys.length > 0) {
        for (const fk of tableData.foreignKeys) {
          if (!fk.name || !fk.columns || fk.columns.length === 0 || 
              !fk.referenceTable || !fk.referenceColumns || fk.referenceColumns.length === 0) {
            continue;
          }
          
          const fkColumns = fk.columns.map(col => `"${col}"`).join(', ');
          const refColumns = fk.referenceColumns.map(col => `"${col}"`).join(', ');
          
          let constraint = `  FOREIGN KEY (${fkColumns}) REFERENCES "${fk.referenceTable}" (${refColumns})`;
          
          // 添加级联操作
          if (fk.updateRule) {
            constraint += ` ON UPDATE ${fk.updateRule}`;
          }
          
          if (fk.deleteRule) {
            constraint += ` ON DELETE ${fk.deleteRule}`;
          }
          
          columnDefinitions.push(constraint);
        }
      }
      
      sql += columnDefinitions.join(',\n');
      sql += '\n);';
      
      // 添加索引（SQLite中索引在表创建后创建）
      if (tableData.indexes && tableData.indexes.length > 0) {
        for (const index of tableData.indexes) {
          if (!index.name || !index.columns || index.columns.length === 0) {
            continue;
          }
          
          const indexColumns = index.columns.map(col => `"${col}"`).join(', ');
          const unique = index.type.toUpperCase() === 'UNIQUE' ? 'UNIQUE ' : '';
          
          sql += `\n\nCREATE ${unique}INDEX "${index.name}" ON "${tableData.name}" (${indexColumns});`;
        }
      }
      
      return sql;
    },
    
    // 生成修改表SQL
    generateAlterSQL() {
      return `-- SQLite不支持完整的ALTER TABLE语法。\n-- 对于大多数结构更改，需要创建新表、迁移数据并重命名表。\n\n/* 请参考SQLite文档了解表结构更改的正确方法。 */`;
    }
  };
};

// SQL Server SQL生成器
const getSQLServerGenerator = () => {
  return {
    // 生成创建表SQL
    generateCreateSQL(tableData) {
      const schema = (tableData.schema || tableData.advancedOptions?.schema || 'dbo');
      let sql = `CREATE TABLE [${schema}].[${tableData.name}] (\n`;
      
      // 添加列定义
      const columnDefinitions = tableData.columns.map(column => {
        let def = `  [${column.name}] ${column.type.toUpperCase()}`;
        
        // 添加长度或值
        if (column.length && this.needsLength(column.type)) {
          def += `(${column.length})`;
        }
        
        // 自增
        if (column.autoIncrement || column.identity) {
          def += ' IDENTITY(1,1)';
        }
        
        // 不为空
        if (column.notNull) {
          def += ' NOT NULL';
        } else {
          def += ' NULL';
        }
        
        // 默认值约束将在表创建后添加
        
        return def;
      });
      
      sql += columnDefinitions.join(',\n');
      
      // 添加主键约束
      const primaryColumns = tableData.columns
        .filter(col => col.primaryKey)
        .map(col => `[${col.name}]`);
        
      if (primaryColumns.length > 0) {
        const pkName = `PK_${tableData.name}`;
        sql += `,\n  CONSTRAINT [${pkName}] PRIMARY KEY ${tableData.advancedOptions?.clusteredPK ? 'CLUSTERED' : 'NONCLUSTERED'} (${primaryColumns.join(', ')})`;
      }
      
      // 添加外键约束
      if (tableData.foreignKeys && tableData.foreignKeys.length > 0) {
        for (const fk of tableData.foreignKeys) {
          if (!fk.name || !fk.columns || fk.columns.length === 0 || 
              !fk.referenceTable || !fk.referenceColumns || fk.referenceColumns.length === 0) {
            continue;
          }
          
          const fkColumns = fk.columns.map(col => `[${col}]`).join(', ');
          const refColumns = fk.referenceColumns.map(col => `[${col}]`).join(', ');
          const refSchema = schema; // 简化处理，实际中可能是不同的Schema
          
          let constraint = `  CONSTRAINT [${fk.name}] FOREIGN KEY (${fkColumns}) REFERENCES [${refSchema}].[${fk.referenceTable}] (${refColumns})`;
          
          // 添加级联操作
          if (fk.updateRule) {
            constraint += ` ON UPDATE ${fk.updateRule}`;
          }
          
          if (fk.deleteRule) {
            constraint += ` ON DELETE ${fk.deleteRule}`;
          }
          
          sql += `,\n${constraint}`;
        }
      }
      
      sql += '\n)';
      
      // 添加高级选项
      if (tableData.advancedOptions && tableData.advancedOptions.custom) {
        sql += `\n${tableData.advancedOptions.custom}`;
      }
      
      sql += ';\n';
      
      // 添加默认值约束
      tableData.columns.forEach(column => {
        if (column.defaultValue) {
          const defaultName = `DF_${tableData.name}_${column.name}`;
          let defaultValue = column.defaultValue;
          
          if (['CURRENT_TIMESTAMP', 'GETDATE()'].includes(column.defaultValue.toUpperCase())) {
            defaultValue = 'GETDATE()';
          } else if (defaultValue.toUpperCase() !== 'NULL') {
            defaultValue = `'${defaultValue}'`;
          }
          
          sql += `\nALTER TABLE [${schema}].[${tableData.name}] ADD CONSTRAINT [${defaultName}] DEFAULT ${defaultValue} FOR [${column.name}];`;
        }
      });
      
      // 添加列描述
      tableData.columns.forEach(column => {
        if (column.comment) {
          sql += `\nEXEC sp_addextendedproperty @name = N'MS_Description', @value = N'${column.comment}', @level0type = N'SCHEMA', @level0name = N'${schema}', @level1type = N'TABLE', @level1name = N'${tableData.name}', @level2type = N'COLUMN', @level2name = N'${column.name}';`;
        }
      });
      
      // 添加表描述
      if (tableData.comment) {
        sql += `\nEXEC sp_addextendedproperty @name = N'MS_Description', @value = N'${tableData.comment}', @level0type = N'SCHEMA', @level0name = N'${schema}', @level1type = N'TABLE', @level1name = N'${tableData.name}';`;
      }
      
      // 添加索引
      if (tableData.indexes && tableData.indexes.length > 0) {
        for (const index of tableData.indexes) {
          if (!index.name || !index.columns || index.columns.length === 0) {
            continue;
          }
          
          const indexColumns = index.columns.map(col => `[${col}]`).join(', ');
          const indexType = this.getSQLServerIndexType(index.type);
          
          sql += `\n\nCREATE ${indexType} INDEX [${index.name}] ON [${schema}].[${tableData.name}] (${indexColumns});`;
        }
      }
      
      return sql;
    },
    
    // 生成修改表SQL
    generateAlterSQL(tableData) {
      const schema = (tableData.schema || tableData.advancedOptions?.schema || 'dbo');
      let sql = `-- 修改表 ${schema}.${tableData.name}\n`;
      
      // 表重命名示例
      sql += `-- 重命名表\n-- EXEC sp_rename '[${schema}].[old_name]', '${tableData.name}';\n\n`;
      
      // 添加列示例
      sql += `-- 添加列\n-- ALTER TABLE [${schema}].[${tableData.name}] ADD [new_column] NVARCHAR(255) NULL;\n\n`;
      
      // 修改列示例
      sql += `-- 修改列\n-- ALTER TABLE [${schema}].[${tableData.name}] ALTER COLUMN [column_name] NVARCHAR(255) NULL;\n\n`;
      
      // 添加约束示例
      sql += `-- 添加约束\n-- ALTER TABLE [${schema}].[${tableData.name}] ADD CONSTRAINT [constraint_name] CHECK (condition);\n\n`;
      
      // 表注释
      if (tableData.comment) {
        sql += `-- 设置表描述\nEXEC sp_addextendedproperty @name = N'MS_Description', @value = N'${tableData.comment}', @level0type = N'SCHEMA', @level0name = N'${schema}', @level1type = N'TABLE', @level1name = N'${tableData.name}';\n\n`;
      }
      
      return sql + '/* 注意: 这只是示例。实际的ALTER语句需要根据与当前表结构的差异自动生成。 */';
    },
    
    // 将通用索引类型转换为SQL Server索引类型
    getSQLServerIndexType(genericType) {
      switch (genericType.toUpperCase()) {
        case 'UNIQUE':
          return 'UNIQUE';
        case 'UNIQUE_CLUSTERED':
          return 'UNIQUE CLUSTERED';
        case 'UNIQUE_NONCLUSTERED':
          return 'UNIQUE NONCLUSTERED';
        case 'CLUSTERED':
          return 'CLUSTERED';
        case 'NONCLUSTERED':
          return 'NONCLUSTERED';
        default:
          return 'NONCLUSTERED'; // 默认非聚集索引
      }
    },
    
    // 类型是否需要长度
    needsLength(type) {
      return ['varchar', 'nvarchar', 'char', 'nchar', 'binary', 'varbinary',
              'decimal', 'numeric', 'float'].includes(type);
    }
  };
};

// DaMeng SQL生成器
const getDaMengGenerator = () => {
  return {
    // 生成创建表SQL
    generateCreateSQL(tableData) {
      let sql = `CREATE TABLE "${tableData.name}" (\n`;
      
      // 添加列定义
      const columnDefinitions = tableData.columns.map(column => {
        let def = `  "${column.name}" ${column.type.toUpperCase()}`;
        
        // 添加长度或精度，考虑字节/字符语义
        if (column.length && this.needsLength(column.type)) {
          // 对于字符类型，考虑语义
          if (this.isCharType(column.type)) {
            const semanticType = column.semanticType || 'BYTE';
            def += `(${column.length} ${semanticType})`;
          } else {
            def += `(${column.length})`;
          }
        } else if (column.precision && this.needsPrecision(column.type)) {
          if (column.scale) {
            def += `(${column.precision},${column.scale})`;
          } else {
            def += `(${column.precision})`;
          }
        }
        
        // 不为空
        if (column.notNull) {
          def += ' NOT NULL';
        }
        
        // 自增 (DaMeng使用IDENTITY代替AUTO_INCREMENT)
        if (column.autoIncrement) {
          def += ' IDENTITY';
        }
        
        // 默认值
        if (column.defaultValue) {
          if (['CURRENT_TIMESTAMP', 'SYSDATE', 'SYSTIMESTAMP', 'NULL'].includes(column.defaultValue.toUpperCase())) {
            def += ` DEFAULT ${column.defaultValue.toUpperCase()}`;
          } else {
            def += ` DEFAULT '${column.defaultValue}'`;
          }
        }
        
        return def;
      });
      
      sql += columnDefinitions.join(',\n');
      
      // 添加主键
      const primaryColumns = tableData.columns
        .filter(col => col.primaryKey)
        .map(col => `"${col.name}"`);
        
      if (primaryColumns.length > 0) {
        sql += `,\n  PRIMARY KEY (${primaryColumns.join(', ')})`;
      }
      
      // 添加索引
      if (tableData.indexes && tableData.indexes.length > 0) {
        for (const index of tableData.indexes) {
          if (!index.name || !index.columns || index.columns.length === 0) {
            continue; // 跳过无效索引
          }
          
          const indexColumns = index.columns.map(col => `"${col}"`).join(', ');
          sql += `,\n  ${index.type === 'UNIQUE' ? 'UNIQUE' : 'INDEX'} "${index.name}" (${indexColumns})`;
        }
      }
      
      // 结束表定义
      sql += '\n)';
      
      // 添加高级选项
      if (tableData.advancedOptions) {
        const options = tableData.advancedOptions;
        
        // 表空间
        if (options.tablespace) {
          sql += `\nTABLESPACE ${options.tablespace}`;
        }
        
        // NLS长度语义（使用会话参数设置）
        if (options.lengthSemantics) {
          sql += `;\n\n-- 设置会话默认字符长度语义\nALTER SESSION SET NLS_LENGTH_SEMANTICS = ${options.lengthSemantics}`;
        }
      }
      
      // 达梦不支持表级选项，这里只添加注释
      if (tableData.comment) {
        sql += `;\n\nCOMMENT ON TABLE "${tableData.name}" IS '${tableData.comment}'`;
      }
      
      // 为列添加注释
      for (const column of tableData.columns) {
        if (column.comment) {
          sql += `;\nCOMMENT ON COLUMN "${tableData.name}"."${column.name}" IS '${column.comment}'`;
        }
      }
      
      return sql;
    },
    
    // 生成修改表SQL
    generateAlterSQL(tableData) {
      let sql = `-- 修改表 ${tableData.name}\n\n`;
      
      // 表重命名示例
      sql += `-- 重命名表\n-- RENAME TABLE "${tableData.name}" TO "new_name";\n\n`;
      
      // 添加列示例
      sql += `-- 添加列\n-- ALTER TABLE "${tableData.name}" ADD "${tableData.columns[0]?.name || 'new_column'}" VARCHAR(255);\n\n`;
      
      // 修改列示例
      sql += `-- 修改列类型\n-- ALTER TABLE "${tableData.name}" MODIFY "${tableData.columns[0]?.name || 'column_name'}" VARCHAR(255);\n\n`;
      
      // 删除列示例
      sql += `-- 删除列\n-- ALTER TABLE "${tableData.name}" DROP COLUMN "${tableData.columns[0]?.name || 'column_name'}";\n\n`;
      
      // 添加主键示例
      sql += `-- 添加主键\n-- ALTER TABLE "${tableData.name}" ADD PRIMARY KEY ("id");\n\n`;
      
      // 添加索引示例
      sql += `-- 添加索引\n-- CREATE INDEX "idx_name" ON "${tableData.name}" ("column_name");\n\n`;
      
      // 表注释
      if (tableData.comment) {
        sql += `-- 设置表注释\nCOMMENT ON TABLE "${tableData.name}" IS '${tableData.comment}';\n\n`;
      }
      
      // 列注释示例
      if (tableData.columns.length > 0) {
        sql += `-- 设置列注释\nCOMMENT ON COLUMN "${tableData.name}"."${tableData.columns[0].name}" IS '列描述';\n\n`;
      }
      
      return sql + '/* 注意: 这只是示例。实际的ALTER语句需要根据与当前表结构的差异自动生成。 */';
    },
    
    // 类型是否需要长度
    needsLength(type) {
      return ['varchar', 'varchar2', 'char', 'nchar', 'nvarchar', 'binary', 'varbinary'].includes(type.toLowerCase());
    },
    
    // 类型是否需要精度
    needsPrecision(type) {
      return ['number', 'decimal', 'numeric', 'float'].includes(type.toLowerCase());
    },
    
    // 判断是否为字符类型
    isCharType(type) {
      if (!type) return false;
      const lowerType = type.toLowerCase();
      return lowerType.includes('char') || lowerType.includes('varchar') || 
             lowerType.includes('varchar2');
    }
  };
};

// 复制到剪贴板
const copyToClipboard = () => {
  navigator.clipboard.writeText(generatedSql.value).then(() => {
    copied.value = true;
    setTimeout(() => {
      copied.value = false;
    }, 2000);
  });
};
</script>

<style scoped>
.table-sql-preview {
  padding: 16px 0;
}

pre {
  font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
  tab-size: 4;
}

.fade-out {
  animation: fadeOut 2s forwards;
}

@keyframes fadeOut {
  0% { opacity: 1; }
  70% { opacity: 1; }
  100% { opacity: 0; }
}

:deep(.el-input__wrapper) {
  @apply shadow-none rounded-md;
}

:deep(.el-input__wrapper:hover) {
  @apply border-gray-400;
}

:deep(.el-input__wrapper.is-focus) {
  @apply border-blue-500 ring-1 ring-blue-500;
}

:deep(.el-select .el-input__wrapper) {
  @apply shadow-none;
}

:deep(.el-select-dropdown__item) {
  @apply text-sm py-2;
}
</style> 